package win.larryzeal.spring.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.nio.charset.StandardCharsets;
import java.util.EnumSet;

/**
 * Created by 张少昆 on 2017/8/25.
 */
//@Order(-10)
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException{
        // 设置存活时间半小时，单位为秒
        servletContext.getSessionCookieConfig().setMaxAge(60 * 60);
        // Session监听器
        // servletContext.addListener(new HttpSessionEventPublisher());

        //  *************** EncodingFilter解决编码问题 ***************
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding(StandardCharsets.UTF_8.displayName());
        encodingFilter.setForceEncoding(true);
        FilterRegistration.Dynamic encodingFilterRegistration = servletContext.addFilter("encodingFilter", encodingFilter);
        encodingFilterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC), false, "/*");

        //  ***************** Spring Security权限认证 *****************取代了SecurityWebAppInitializer extends AbstractSecurityWebApplicationInitializer
        FilterRegistration.Dynamic securityFilterRegistration = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
        securityFilterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC), false, "/*");

        super.onStartup(servletContext);
    }

    @Override
    protected Class<?>[] getRootConfigClasses(){
        return new Class[]{AppConfig.class,DataSourceConfig.class,DataSourceFineConfig.class,SecurityConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses(){
        return new Class[]{MvcConfig.class};
    }

    @Override
    protected String[] getServletMappings(){
        return new String[]{"/"};
    }

}
